package com.ruoyi.modbus;

import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.slave.ModbusSlave;
import com.intelligt.modbus.jlibmodbus.slave.ModbusSlaveFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;
import java.net.InetAddress;

public class ModbusSlaveExample {
    public static void main(String[] args) {
        try {
            // 1. 配置TCP参数
            TcpParameters params = new TcpParameters();
            params.setHost(InetAddress.getByName("0.0.0.0"));
            params.setPort(502);
            params.setKeepAlive(true);

            // 2. 创建Modbus从站实例
            ModbusSlave slave = ModbusSlaveFactory.createModbusSlaveTCP(params);
            slave.setServerAddress(1); // 设置从站ID

            // 3. 初始化寄存器数据
            int[] holdingRegisters = new int[100];
            for (int i = 0; i < holdingRegisters.length; i++) {
                holdingRegisters[i] = i * 10;
            }
//            slave.getHoldingRegisters().set(0, holdingRegisters);

            // 4. 启动从站服务
            Modbus.setAutoIncrementTransactionId(true);
            slave.listen();

            System.out.println("Modbus TCP从站已启动，监听端口: " + params.getPort());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
